package com.collectplus.express.tools;

import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.ContactsContract;
import droid.frame.utils.lang.Str;

/**
 * 系统通讯录工具类
 * 
 * @author coffee<br>
 *         2015-6-26上午10:04:41
 */
public class ContactUtils {
	/**
	 * 返回姓名、手机号
	 * 
	 * @param contactUri
	 * @return
	 */
	public String[] getContactPhone(Activity context, Uri contactUri) throws Exception {
		@SuppressWarnings("deprecation")
		Cursor cursor = context.managedQuery(contactUri, null, null, null, null);
		cursor.moveToFirst();// 注意不能落
		int phoneColumn = cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);
		int hasPhoneNum = cursor.getInt(phoneColumn);
		String phoneCode = ""; // 手机号
		String phoneName = ""; // 联系人姓名
		if (hasPhoneNum > 0) {
			// 获得联系人的ID号
			int idColumn = cursor.getColumnIndex(ContactsContract.Contacts._ID);
			String contactId = cursor.getString(idColumn);
			// 获得联系人的电话号码的cursor;
			Cursor phones = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null,
					null);
			// int phoneCount = phones.getCount();
			// allPhoneNum = new ArrayList<String>(phoneCount);
			if (phones.moveToFirst()) {
				// 遍历所有的电话号码
				for (; !phones.isAfterLast(); phones.moveToNext()) {
					int numberIndex = phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
					int nameIndex = phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
					//
					int typeIndex = phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE);
					int phoneType = phones.getInt(typeIndex);
					// /
					switch (phoneType) {
					case 2:
						phoneCode = phones.getString(numberIndex);
						phoneName = phones.getString(nameIndex);
						break;
					}
					// allPhoneNum.add(phoneNumber);
				}
				phones.close();
			}
		}
		// Attempted to access a cursor after it has been closed.
		if (Build.VERSION.SDK_INT < 14) {
			if (cursor.isClosed() == false) {
				cursor.close();
			}
		}
		phoneCode = Str.formatPhone(phoneCode);
		phoneName = phoneName.trim();
		return new String[] { phoneName, phoneCode };
	}
}
